﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Net;
using System.Net.Mail;
using System.Threading;
using Microsoft.WindowsAzure.ServiceRuntime;
using AzureQueue;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;

namespace EmailAgent
{
    public class WorkerRole : RoleEntryPoint
    {
        void ProcessEmail(EmailEnity email)
        {
            var mailMessage = new MailMessage { From = new MailAddress(email.From) };
            mailMessage.To.Add(new MailAddress(email.To));
            mailMessage.Subject = email.Subject;
            mailMessage.Body = email.Body;
            mailMessage.IsBodyHtml = true;

            // Send the email
            var client = new SmtpClient();
            client.Send(mailMessage);
        }

        void ProcessEmailsInQueue()
        {
            EmailEnity email;
            var queuDataSource = new AzureQueueDataSource();
            CloudQueueMessage queueMessage;

            while (queuDataSource.GetEmail(out email, out queueMessage))
                try
                {
                    // Try to send the message 3 times, if that fails then leave the message on the queue for logging reasons
                    if (queueMessage.DequeueCount < int.Parse(ConfigurationManager.AppSettings["NumberOfSendEmailRetries"]))
                    {
                        ProcessEmail(email);
                        queuDataSource.DeleteEmail(queueMessage);
                    }
                }
                catch (Exception exception)
                {
                    Trace.TraceError("E-mail queue: {0}", exception.ToString());
                }
        }

        public override void Run()
        {
            while (true)
            {
                try
                {
                    ProcessEmailsInQueue();
                }
                catch (Exception exception)
                {
                    Trace.TraceError("E-mail queue: {0}", exception.ToString());
                }
                finally
                {
                    Thread.Sleep(TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["NumberOfSecondsQueuePollSleep"])));                    
                }
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = int.Parse(ConfigurationManager.AppSettings["DefaultConnectionLimit"]);

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            return base.OnStart();
        }

    }
}
